﻿Imports System.Data.SqlClient
Imports System.Drawing.Printing

Public Class Expedition

    Private user As String
    Private cn As CnData
    Private da As SqlDataAdapter
    Private ds As DataSet
    Private cmd As SqlCommand
    Private dtr As SqlDataReader
    Private chargement As String
    Private recherche As Boolean
    Private reprise As Boolean

    Public Sub New(ByVal user As String, ByRef cn As CnData, ByVal charg As String, ByVal reprise As Boolean)
        ' Cet appel est requis par le concepteur.
        InitializeComponent()

        ' Ajoutez une initialisation quelconque après l'appel InitializeComponent().
        Me.user = user
        Me.cn = cn
        Me.chargement = charg
        Me.reprise = reprise

    End Sub

    Private Sub Agres_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Agres.KeyDown
        If e.KeyCode = Keys.Enter Then
            If String.IsNullOrEmpty(Agres.Text) Then
                MsgBox("Numero de colis incorrect", MsgBoxStyle.ApplicationModal)
                Agres.Text = Nothing
                Exit Sub
            End If
            If Not IsNumeric(Agres.Text) Then
                MsgBox("Veuillez activer la touche MAJ", MsgBoxStyle.ApplicationModal)
                Agres.Text = Nothing
                Exit Sub
            End If
            Try
                ScanDS.Tables("ScanLP").Rows.Add(New String() {Agres.Text})
            Catch ex As Exception

            End Try
            Agres.Text = Nothing

            ListeLP.Sort(ListeLP.Columns(0), System.ComponentModel.ListSortDirection.Descending)
            ListeLP.Rows(0).Selected = True
            'MsgBox(ListeLP.Columns(0).)
            recherche = True
            If Not RechercheAgres.IsBusy Then
                RechercheAgres.RunWorkerAsync()
            End If
            Cpt.Text = ScanLP.Rows.Count
        End If

    End Sub

    Private Sub Expedition_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Me.DialogResult = Windows.Forms.DialogResult.OK
        RechercheAgres.CancelAsync()
        recherche = False
        cn.Close()
    End Sub


    Private Sub Expedition_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'TODO: cette ligne de code charge les données dans la table 'LaisserPasserDS.BL'. Vous pouvez la déplacer ou la supprimer selon vos besoins.
        Me.BLTableAdapter.Fill(Me.LaisserPasserDS.BL, "")
        'TODO: cette ligne de code charge les données dans la table 'LaisserPasserDS.BLdétails'. Vous pouvez la déplacer ou la supprimer selon vos besoins.
        Me.BLdétailsTableAdapter.Fill(Me.LaisserPasserDS.BLdétails, "")


        Cpt.Text = ScanDS.Tables("ScanLP").Rows.Count
        NumChar.Text = chargement
        recherche = False
        'RechercheAgres.RunWorkerAsync()

        If reprise Then
            cn.Open()
            cmd = New SqlCommand("SELECT LP " _
                                        & " FROM BrouillonC " _
                                        & " WHERE     (Chargement = '" & chargement & "')", cn.getCn)
            dtr = cmd.ExecuteReader

            While dtr.Read()
                Try
                    ScanDS.Tables("ScanLP").Rows.Add(New String() {dtr.Item("LP").ToString})
                Catch ex As Exception
                End Try
            End While

            dtr.Close()
            cn.Close()
        End If
        Agres.Text = Nothing
        ListeLP.Sort(ListeLP.Columns(0), System.ComponentModel.ListSortDirection.Descending)
        'ListeLP.Rows(0).Selected = True
        'MsgBox(ListeLP.Columns(0).)
        recherche = True
        If Not RechercheAgres.IsBusy Then
            RechercheAgres.RunWorkerAsync()
        End If
        Cpt.Text = ScanLP.Rows.Count
    End Sub

    Private Sub RechercheAgres_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles RechercheAgres.DoWork
        Dim arg As Integer = 0
        Do While True
            If recherche Then
                'valider.Enabled = False
                If ListeLP.RowCount <= 0 Then
                    recherche = False
                    Exit Sub
                End If

                cn.Open()
                For i = arg To ListeLP.Rows(0).Cells(0).Value Step 1
                    Try
                        For Each dr As DataRow In ScanLP.Select("DateAdd=" & i)
                            cmd = New SqlCommand("SELECT     LP.LP, LP.TypeAgres, LP.NombreColis, Flux.NomFlux, SpeLP.Spe " _
                                        & "FROM         LP LEFT OUTER JOIN " _
                                        & "Flux ON LP.Flux = Flux.NumFlux LEFT OUTER JOIN " _
                                        & "SpeLP ON LP.LP = SpeLP.LP " _
                                        & "WHERE     (LP.LP = '" & dr.Item("LP") & "')", cn.getCn)
                            dtr = cmd.ExecuteReader

                            dr.BeginEdit()
                            If dtr.Read() Then
                                dr.Item("TypeAgres") = dtr.Item("TypeAgres")
                                dr.Item("NbColis") = dtr.Item("NombreColis")
                                dr.Item("TypeFlux") = dtr.Item("NomFlux")
                                dr.Item("Spe") = dtr.Item("Spe")
                                dr.Item("Statut") = "Chargé"
                                dtr.Close()
                            Else
                                dtr.Close()
                                cmd = New SqlCommand("INSERT INTO LP (LP,Expediteur,Destinataire,Flux,TypeAgres,NombreColis,DateImp,UtilImp,Statut) VALUES ('" & dr.Item("LP") & "','00','00','00','',1,'" & Date.Today & "','" & user & "','Créé')", cn.getCn())
                                cmd.ExecuteNonQuery()

                                dr.Item("Statut") = "Chargé"
                            End If
                            'dtr.Close()
                            dr.EndEdit()
                        Next
                    Catch ex As Exception

                    End Try
                    arg = i + 1
                Next
                cn.Close()
                'valider.Enabled = True
                If ListeLP.Rows(0).Cells(0).Value = arg - 1 Then recherche = False
            Else
                System.Threading.Thread.Sleep(300)
            End If
        Loop

    End Sub

    '{D0782,1016,0762|}
    '{C|}
    '{XB00;0200,0490,A,3,03,0,0128,+0000000000,000,0,00|}
    '{RB00;>5123456789012345678|}
    '{PV00;0260,0656,0042,0042,H,00,B=123456789012345678|}
    '{LC;0000,0668,0910,0668,0,3|}
    '{PV01;0030,0715,0042,0042,H,00,B=CDE|}
    '{LC;0189,0671,0189,0761,0,3|}
    '{LC;0718,0671,0718,0761,0,3|}
    '{PV02;0220,0716,0042,0042,H,00,B=000000000000000000*|}
    '{PV03;0740,0715,0042,0042,H,00,B=999/999|}
    '{PV04;0979,0730,0035,0035,H,33,B=123456789012345678|}
    '{PV05;0979,0350,0035,0035,H,33,B=123456789012345678|}
    '{LC;0000,0469,0910,0469,0,3|}
    '{PV06;0470,0449,0028,0056,H,00,B=Mmmmmmmmmmmmmmmmmm|}
    '{PV07;0310,0449,0028,0056,H,00,B=Fournisseur:|}
    '{PV08;0420,0379,0028,0056,H,00,B=Mmmmmmmmmmmmmmmmmmmm|}
    '{PV09;0310,0379,0028,0056,H,00,B=Secteur:|}
    '{PV10;0520,0309,0028,0056,H,00,B=Mmmmmmmmmmmmmmmm|}
    '{PV11;0310,0309,0028,0056,H,00,B=Zone de roulage:|}
    '{LC;0000,0259,0910,0259,0,3|}
    '{PV12;0520,0239,0028,0056,H,00,B=RAYON:|}
    '{PV13;0030,0239,0028,0056,H,00,B=VERS:|}
    '{PV14;0130,0239,0028,0056,H,00,B=HSM COUPOLE|}
    '{PV15;0030,0169,0028,0056,H,00,B=DE:|}
    '{PV16;0090,0169,0028,0056,H,00,B=HSM MAISON|}
    '{PV17;0640,0239,0028,0056,H,00,B=000|}
    '{PV18;0520,0169,0028,0056,H,00,B=DATE:|}
    '{PV19;0620,0169,0028,0056,H,00,B=00/00/00|}
    '{LC;0000,0189,0910,0189,0,3|}
    '{LC;0000,0119,0910,0119,0,3|}
    '{LC;0499,0120,0499,0260,0,3|}
    '{LC;0299,0255,0299,0465,0,3|}
    '{PV20;0030,0086,0063,0063,H,00,B=INTER COQUE MAGASIN|}
    '{LC;0300,0399,0914,0399,0,3|}
    '{LC;0300,0329,0914,0329,0,3|}
    '{LC;0000,0359,0300,0359,0,3|}
    '{PV21;0030,0324,0049,0049,H,00,B=PENDERIE|}
    '{PV22;0030,0424,0049,0049,H,00,B=888|}
    '{XS;I,0001,0000C6201|}

    Private Sub ListeLP_RowHeaderMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles ListeLP.RowHeaderMouseDoubleClick
        If e.RowIndex >= 0 Then
            ListeLP.Rows.RemoveAt(e.RowIndex)
        End If
    End Sub

    Private Sub ListeLP_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles ListeLP.RowsRemoved
        Cpt.Text = ListeLP.RowCount
    End Sub

    Private Sub valider_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles valider.Click
        If ScanLP.Rows.Count < 1 Then
            MsgBox("Vous n'avez pas scanné d'agrès")
            Exit Sub
        End If
        valider.Enabled = False
        Me.Cursor = Cursors.WaitCursor
        cn.Open()
        cmd = New SqlCommand("DELETE FROM BrouillonC WHERE (Chargement = '" & chargement & "')", cn.getCn)
        cmd.ExecuteScalar()

        Dim type, temp As String
        Dim nbcol As Integer = 0
        type = "Mono"
        temp = ScanLP.Rows(0).Item("TypeFlux").ToString
        If Not IsDBNull(ScanLP.Compute("Sum(NbColis)", "")) Then
            nbcol = ScanLP.Compute("Sum(NbColis)", "")
        End If
        'nbcol = nbcol + ScanLP.Compute("Sum(NbColis)", "")
        For Each dr As DataRow In ScanLP.Rows
            If temp <> dr.Item("TypeFlux").ToString Then type = "Multi"
            cmd = New SqlCommand("INSERT INTO LP_Chargement (LP,chargement) VALUES ('" & dr.Item("LP") & "','" & NumChar.Text & "')", cn.getCn)
            cmd.ExecuteNonQuery()
            cmd = New SqlCommand("UPDATE LP SET Statut = 'Non reçu' WHERE LP = '" & dr.Item("LP") & "'", cn.getCn)
            cmd.ExecuteNonQuery()
        Next
        cmd = New SqlCommand("UPDATE Chargements SET DateExp='" & Date.Today & "'," _
                             & "HeureExp='" & FormatDateTime(Date.Now, DateFormat.LongTime) & "'," _
                             & "Statut='Transit'," _
                             & "NbAgres=" & Cpt.Text & "," _
                             & "NbColis=" & nbcol & "," _
                             & "TypeFlux='" & type & "'," _
                             & "UtilExp='" & user & "' WHERE chargement='" & NumChar.Text & "'", cn.getCn)
        If cmd.ExecuteNonQuery() > 0 Then
            Me.BLdétailsTableAdapter.ClearBeforeFill = True
            Me.BLTableAdapter.ClearBeforeFill = True

            'TODO: cette ligne de code charge les données dans la table 'LaisserPasserDataSet.BL'. Vous pouvez la déplacer ou la supprimer selon vos besoins.
            Me.BLTableAdapter.Fill(Me.LaisserPasserDS.BL, NumChar.Text)
            'TODO: cette ligne de code charge les données dans la table 'LaisserPasserDataSet.ListeLP'. Vous pouvez la déplacer ou la supprimer selon vos besoins.
            Me.BLdétailsTableAdapter.Fill(Me.LaisserPasserDS.BLdétails, NumChar.Text)

            Dim print As New PageSettings
            print.Margins.Bottom = 20
            print.Margins.Top = 20
            print.Margins.Left = 35
            print.Margins.Right = 35
            print.PrinterSettings.Copies = 2
            Dim p As New Microsoft.Reporting.WinForms.ReportParameter("Duplicata", "False")
            Me.ReportViewer1.LocalReport.SetParameters(p)
            Me.ReportViewer1.SetPageSettings(print)
            Me.ReportViewer1.RefreshReport()


            'Dim tmp As String = Me.ReportViewer1.LocalReport.ToString
            While Not Me.ReportViewer1.CurrentStatus.CanPrint
                Application.DoEvents()
            End While
            ReportViewer1.PrintDialog(print.PrinterSettings)
            Me.Focus()

            MsgBox("Chargement expédié")
        Else
            MsgBox("Une erreur s'est produite lors de l'écriture des données, chargement non enregistré")
            valider.Enabled = True
            Exit Sub
        End If
        Me.Cursor = Cursors.Default
        ReportViewer1.Dispose()
        cn.Close()
        Me.Close()

    End Sub

    Private Sub Fermer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Close()
    End Sub

    Private Sub brouillon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles brouillon.Click
        If ScanLP.Rows.Count < 1 Then
            MsgBox("Vous n'avez pas scanné d'agrès")
            Exit Sub
        End If
        cn.Open()
        cmd = New SqlCommand("DELETE FROM BrouillonC WHERE (Chargement = '" & chargement & "')", cn.getCn)
        cmd.ExecuteNonQuery()

        Dim type, temp As String
        Dim nbcol As Integer = 0

        type = "Mono"
        temp = ScanLP.Rows(0).Item("TypeFlux").ToString
        If Not IsDBNull(ScanLP.Compute("Sum(NbColis)", "")) Then
            nbcol = ScanLP.Compute("Sum(NbColis)", "")
        End If

        For Each dr As DataRow In ScanLP.Rows
            If temp <> dr.Item("TypeFlux").ToString Then type = "Multi"
            cmd = New SqlCommand("INSERT INTO BrouillonC (LP,chargement) VALUES ('" & dr.Item("LP") & "','" & NumChar.Text & "')", cn.getCn)
            cmd.ExecuteNonQuery()
            'cmd = New SqlCommand("UPDATE LP SET Statut = 'Chargé' WHERE LP = '" & dr.Item("LP") & "'", cn.getCn)
            'cmd.ExecuteNonQuery()
        Next
        cmd = New SqlCommand("UPDATE Chargements SET NbAgres=" & Cpt.Text & "," _
                             & "NbColis=" & nbcol & "," _
                             & "TypeFlux='" & type & "' WHERE chargement='" & NumChar.Text & "'", cn.getCn)
        If cmd.ExecuteNonQuery() > 0 Then
            MsgBox("Brouillon enregistré")
        Else
            MsgBox("Une erreur s'est produite lors de l'écriture des données, brouillon non enregistré")
        End If

        cn.Close()
        Me.Close()

    End Sub
End Class